package com.example.clock_demo.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.clock_demo.common.Result;
import com.example.clock_demo.entitys.Shift;
import com.example.clock_demo.service.ShiftService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 班次管理相关的API接口
 */
@RestController
@RequestMapping("/shifts")
@Api(tags = "班次管理")
public class ShiftController {


    @Resource
    private ShiftService shiftService;

    /**
     * 导入班次信息
     * @param file Excel 文件
     * @return 操作结果字符串
     * @throws IOException 文件读取可能抛出IO异常
     */
    @PostMapping("/import")
    @ResponseBody
    @ApiOperation("导入班次信息")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> importShifts(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error("上传失败，文件为空！");
        }
        try {
            shiftService.importShifts(file.getInputStream());
            return Result.success("班次导入成功");
        } catch (Exception e) {
            return Result.error("班次导入失败: " + e.getMessage());
        }
    }

    /**
     * 分页并根据名称模糊查询班次信息
     * @param current 当前页码
     * @param size 每页数量
     * @param name 班次名称 (用于模糊查询, 非必填)
     * @return 分页结果对象
     */
    @GetMapping("/page")
    @ApiOperation("分页查询班次信息")
    @PreAuthorize("hasAnyRole('ADMIN', 'EMPLOYEE')")
    public Result<IPage<Shift>> findPage(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String name) {

        try {
            IPage<Shift> result = shiftService.findPage(current, size, name);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询班次信息失败: " + e.getMessage());
        }
    }



}
